module.exports = app => {
    const express = require('express')
    const AdminUser = require('../../models/AdminUser')
    const jwt = require('jsonwebtoken')
    const assert = require('http-assert')
    const router = express.Router({
            mergeParams: true //表示合并url参数，不然在接口里获取不到req.params.resource
        })
        // const Category = require('../../models/Category')
        //创建资源
    router.post('/', async(req, res) => {
            const model = await req.Model.create(req.body)
            res.send(model)
        })
        //修改资源
    router.put('/:id', async(req, res) => {
            const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
            res.send(model)
        })
        //资源列表
    router.get('/', async(req, res) => {
            const queryOptions = {}
            if (req.Model.modelName === 'Category') {
                queryOptions.populate = 'parent'
            }
            const items = await req.Model.find().setOptions(queryOptions).limit(100)
            res.send(items)
        })
        //资源详情
    router.get('/:id', async(req, res) => {
            const model = await req.Model.findById(req.params.id)
            res.send(model)
        })
        //删除资源
    router.delete('/:id', async function(req, res) {
            await req.Model.findByIdAndDelete(req.params.id, req.body)
            res.send({
                success: true
            })
        })
        //登录授权中间件
    const authMiddleware = require('../../middleware/auth')
        //资源中间件
    const resourceMiddleware = require('../../middleware/resourse')
        //统一模块请求接口
    app.use('/admin/api/rest/:resource', authMiddleware(), resourceMiddleware(), router)

    //获取上传文件
    //express本身获取不到上传文件的数据，需要上传文件的中间件:multer
    const multer = require('multer')
    const upload = multer({ dest: __dirname + '/../../uploads' }) //执行并传目标地址
        //upload.single('file')中间件：表示单个文件的上传
    app.post('/admin/api/upload', authMiddleware(), upload.single('file'), async(req, res) => {
        const file = req.file
        file.url = `http://localhost:3000/uploads/${file.filename}`
        res.send(file)
    })

    app.post('/admin/api/login', async(req, res) => {
        //解构用户提交的用户名和密码
        const { username, password } = req.body
            //根据用户名查询用户
            //select:后台定义时默认不取出password,这里+password表示加上password取出
        const user = await AdminUser.findOne({ username }).select('+password')
        assert(user, 422, '用户不存在')
            // if (!user) {
            //     return res.status(422).send({
            //         message: '用户不存在'
            //     })
            // }
            //校验密码
        const isValid = require('bcrypt').compareSync(password, user.password)
        assert(isValid, 422, '密码错误')
            //返回token
        const token = jwt.sign({ id: user._id }, app.get('secret'))
        res.send({ token })
    })

    //错误处理函数
    app.use(async(err, req, res, next) => {
        res.status(err.statusCode || 500).send({
            message: err.message
        })
    })
}